package com.peter.baselibrary.receiver;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.peter.baselibrary.events.NetworkChangeEvent;
import com.peter.baselibrary.utils.Constants;
import com.peter.baselibrary.utils.NetUtils;

import org.greenrobot.eventbus.EventBus;

public class NetworkConnectChangedReceiver extends BroadcastReceiver {

    private static final String TAG = NetworkConnectChangedReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        SharedPreferences preferences = context.getSharedPreferences(Constants.SP_NET_STATUS, Context.MODE_PRIVATE);
        @SuppressLint("CommitPrefEdits")
        SharedPreferences.Editor editor = preferences.edit();
        //**判断当前的网络连接状态是否可用*/
        boolean isConnected = NetUtils.isConnected(context);
        if (preferences.getBoolean(Constants.NETWORK_STATUS, false) != isConnected) {
            Log.d(TAG, "onReceive: 当前网络 " + isConnected);
            //网络状态缓存，当状态改变时再发送消息
            EventBus.getDefault().post(new NetworkChangeEvent(isConnected));
            editor.putBoolean(Constants.NETWORK_STATUS, isConnected);
            editor.apply();
        }
    }
}
